package com.feishi.core.socket.netty.handler;

import com.feishi.core.socket.common.SocketDecoder;
import com.feishi.core.socket.common.decoder.SplitDecoder;
import com.feishi.core.util.common.bean.ByteBufferProxy;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @version 1.0
 * @auth caixq
 * @time 18-3-28 19:40
 **/
public class NettyDecoderHandler extends ByteToMessageDecoder {
    private byte[] bytesBuffer = new byte[32];
    protected ByteBufferProxy bfp = new ByteBufferProxy(64);

    SocketDecoder decoder= new SplitDecoder('\n','\\');

    public NettyDecoderHandler(SocketDecoder decoder) {
        this.decoder=decoder;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

        int left = in.readableBytes();
        int index = 0;
        while (left > 0) {
            index = left < bytesBuffer.length ? left : bytesBuffer.length;
            in.readBytes(bytesBuffer, 0, index);
            bfp.put(bytesBuffer, 0, index);
            left -= index;
        }


        byte[] result = decoder.decode(this.bfp);


        while (result != null) {
            out.add(decoder.decode(result));
            result = decoder.decode(this.bfp);
        }
        if (bfp.getBf().position() > 1024) {
            System.err.println("bfp.getBf() pakage was too large!!\n the cached data will be clear! ");
            bfp.clear();
        }
    }
}
